package com.mszlu.blog.admin.service;

import com.mszlu.blog.admin.pojo.Admin;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.ArrayList;

/**
 * Created with IntelliJ IDEA.
 * User: SJP
 * Date: 2022/3/8
 * Time: 21:18
 *
 * @author sjp
 * Description: No Description
 */
@Component
@Slf4j
public class SecurityUserService implements UserDetailsService {

    @Autowired
    private AdminService adminService;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        /**
         * 登录的时候，会吧username 传递到这里
         * 通过username查询admin表如果admin存在，将密码告诉spring security
         * 如果不存在，则返回null 认证失败
         */
        log.info("username:{}",username);
        Admin admin = adminService.findAdminByUserName(username);
        if(admin == null) {
            throw new UsernameNotFoundException("用户不存在");
        }

        ArrayList<GrantedAuthority> authorities = new ArrayList<>();
        UserDetails userDetails = new User(username,admin.getPassword(),authorities);
        //剩下的认证就由框架帮我们完成
        return userDetails;

    }

    public static void main(String[] args) {
        System.out.println(new BCryptPasswordEncoder().encode("123456"));
    }
}
